package net.sppan.base.controller.mgActivity;

import com.alibaba.fastjson.JSON;
import net.sppan.base.common.utils.BarcodeUtil;
import net.sppan.base.common.utils.FtpFileUtil;
import net.sppan.base.common.utils.JbarcodeUtil;
import net.sppan.base.dao.EntityManageDaoService;
import net.sppan.base.entity.mgEntity.*;
import net.sppan.base.enumType.*;
import net.sppan.base.service.*;
import org.apache.commons.lang3.StringUtils;
import org.jbarcode.JBarcode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@RestController
@CrossOrigin
public class MgActivityController {

	@Autowired
	private IMgUserService userService;

	@Autowired
	private IMgUserAppointService userAppointService;

    @Autowired
    private IMgUserAwardService userAwardService;

    @Autowired
    private IMgAwardService awardService;

	@Autowired
	private IMgCodeService codeService;

	@Autowired
	private EntityManageDaoService entityManageDaoService;

	@Autowired
	private IMgUserCodeService userCodeService;


	private final String caoedPath="http://mg.linbang.co/image/";

	private final String activityname="2019年上海国际车展";

	private final boolean isSend=false;// todo 是否发送到异步系统 true

	private final String htmlUrl = "http://mg.linbang.co/MG/write.html";
	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 *
	 * 条形码入库
	 * 免费咖啡券  需要核销
	 * 买一增一咖啡券  只需要我这边入库 发送异构系统 不需要核销
	 *
	 */
	
	@RequestMapping(value={"mg/generateUserMgCode"})
	public void  generateUserMgCode(String telephone, String codeType, HttpServletResponse response, String callback){
		Map res = new HashMap<String,String>();
		String path = "";
		File file = null;
		if(StringUtils.isBlank(telephone)||StringUtils.isEmpty(codeType)){
			res.put("status","fail");
			res.put("message","telephone is empty or codeType is empty");
			parseJsonToString(res,callback,response);return ;
		}
		MgUser mgUser = userService.findByTelephone(telephone);

		if(mgUser == null){
			res.put("status","fail");
			res.put("message","user is null ");
			parseJsonToString(res,callback,response);return ;
		}

		MgUserCode mgUserCode1 = userCodeService.findByTelephoneAndCodeType(telephone,codeType);
		if(mgUserCode1!=null&&StringUtils.isNoneBlank(mgUserCode1.getCode())&&mgUserCode1.getCodeType().equals(codeType)){
			res.put("status","ok");
			res.put("again","yes");
			res.put("codeType",codeType);
			res.put("message",mgUserCode1.getCodeUrl());
			parseJsonToString(res,callback,response);return ;
		}
		String codeId = entityManageDaoService.randMgCode(CodeStatusTYpe.WeiLingQu.name(), codeType);
		MgCode code = codeService.findByCode(codeId);

		MgUserCode mgUserCode = new MgUserCode();
		mgUserCode.setCode(code.getCode());
		mgUserCode.setCodeId(code.getId());
		mgUserCode.setCodeStatus(CodeStatusTYpe.LingQuWeiHeXiao.name());
		mgUserCode.setCodeType(codeType);
		mgUserCode.setUserId(mgUser.getId());
		mgUserCode.setUserName(mgUser.getUserName());
		mgUserCode.setTelephone(mgUser.getTelephone());
		code.setCodeStatus(CodeStatusTYpe.LingQuWeiHeXiao.name());

		logger.info("tel:" + telephone + ",领取，" + ",codetype:" + CodeType.getDescByName(codeType) + ",code:" + code.getCode() + ",codeId:" + codeId);
		//产生条形码返回至页面
		String keycode = code.getCode();
		if (keycode != null && !"".equals(keycode)) {
			try {
				//path= ResourceUtils.getURL("classpath:templates/").getPath()+keycode+".png";
				path = "/usr/soft/static/image/"+keycode+".png";
				//file = BarcodeUtil.generate2(keycode, path);

				boolean isSuc = JbarcodeUtil.createBarcode(keycode,new File(path),"");

				//Boolean flag= FtpFileUtil.uploadFile(file.getName(),new FileInputStream(file));
				/*if(file.exists()){
					file.delete();
				}*/

				if(isSuc){
					logger.info("ftp上传成功:"+keycode+".png");
					res.put("status","ok");
					res.put("message",caoedPath+keycode+".png");
					mgUserCode.setCodeUrl(caoedPath+keycode+".png");
					entityManageDaoService.hexiaoCode(code,mgUserCode);
				}else{
					res.put("status","fail");
					res.put("message","服务器繁忙，请稍后再试吧！");
				}
				parseJsonToString(res,callback,response);return ;
			} catch (Exception e) {
				logger.error("生成条形码图片出错", e);
                res.put("status","fail");
                res.put("message","生成条形码出错！");
                parseJsonToString(res,callback,response);return ;
			}
		}
	}

	private static String getImageStr(String filePath) {
		         InputStream inputStream = null;
		         byte[] data = null;
		         try {
			            inputStream = new FileInputStream(filePath);
			            data = new byte[inputStream.available()];inputStream.read(data);
			            inputStream.close();
			        } catch (IOException e) {
			             e.printStackTrace();
			         }
		         // 加密
		         BASE64Encoder encoder = new BASE64Encoder();
		         return encoder.encode(data);
		     }

	/**
	 *
	 * 条形码核销
	 *
	 *
	 */

	@RequestMapping(value={"mg/hexiaoCode"})
	public void hexiaoCode(String code,String callback,HttpServletResponse response) {
		Map res = new HashMap<String,String>();
		if(StringUtils.isBlank(code)){
			res.put("status","fail");

			res.put("message","请先输入核销码！ ");

			parseJsonToString(res,callback,response);return;
		}

		MgCode mgCode = codeService.findByCode(code);

		MgUserCode mgUserCode = null;

		// vip code 先查询数据库
		if(mgCode.getCodeType().equals(CodeType.Vip.name())){

			mgUserCode = userCodeService.findByCode(code);
			if(mgUserCode!=null){
				res.put("status","fail");
				res.put("message","此号码已经核销过，不能重复核销！");
				parseJsonToString(res,callback,response);return;
			}
			mgUserCode = new MgUserCode();
			mgUserCode.setCode(mgCode.getCode());
			mgUserCode.setCodeId(mgCode.getId());
			mgUserCode.setCodeStatus(CodeStatusTYpe.YiHeXiao.name());
			mgUserCode.setCodeType(mgCode.getCodeType());
			userCodeService.save(mgUserCode);

			mgCode.setCodeStatus(CodeStatusTYpe.YiHeXiao.name());
			mgUserCode.setResigntime(System.currentTimeMillis());
			mgUserCode.setCodeStatus(CodeStatusTYpe.YiHeXiao.name());
			entityManageDaoService.hexiaoCode(mgCode,mgUserCode);

			res.put("status","ok");
			res.put("message","核销成功 ");
			res.put("telephone","VIp咖啡券电话号码未知！");
			res.put("userName","VIp咖啡券姓名未知！");
			parseJsonToString(res,callback,response);return;

		}else{
			mgUserCode = userCodeService.findByCode(code);
		}

		if(mgCode == null || mgUserCode == null){
			res.put("status","fail");
			res.put("message","系统不存在此核销码，请确认是否正确！");
			parseJsonToString(res,callback,response);return;
		}

		if(mgCode.getCodeType().equalsIgnoreCase(CodeType.Buy_one_send_one.name())){
			res.put("status","fail");

			res.put("message","系统不存在此免费咖啡券核销码，请确认是否正确！ ");
			parseJsonToString(res,callback,response);return;
		}

		if(!mgCode.getCodeStatus().equalsIgnoreCase(CodeStatusTYpe.LingQuWeiHeXiao.name())){
			res.put("status","fail");

			res.put("message","此号码已经核销过，不能重复核销！ ");
			parseJsonToString(res,callback,response);return;
		}

		mgCode.setCodeStatus(CodeStatusTYpe.YiHeXiao.name());
		mgUserCode.setResigntime(System.currentTimeMillis());
		mgUserCode.setCodeStatus(CodeStatusTYpe.YiHeXiao.name());
		entityManageDaoService.hexiaoCode(mgCode,mgUserCode);

		res.put("status","ok");
		res.put("message","核销成功 ");
		res.put("telephone",mgUserCode.getTelephone());
		res.put("userName",mgUserCode.getUserName());
		parseJsonToString(res,callback,response);return;
	}


	/**
	 *
	 * 查询用户信息
	 * @param telephone
	 * @return
	 */
	@RequestMapping(value={"mg/queryMgUser"})
	public void queryMgUser(String telephone, String callback, HttpServletResponse response){
		logger.info("queryMgUser telephone："+telephone+",");
		Map res = new HashMap<String,String>();

		if(StringUtils.isEmpty(telephone)){
			res.put("status","fail");

			res.put("message","电话号不能为空");
			 parseJsonToString(res,callback,response);return;
		}
		MgUser mgUser = userService.findByTelephone(telephone);

		if(mgUser == null){
			res.put("status","fail");

			res.put("message","用户不存在");
			parseJsonToString(res,callback,response);return;
		}

		res.put("status","ok");

		res.put("message",mgUser);

		parseJsonToString(res,callback,response);return;
	}


	@RequestMapping(value={"mg/appointmentNumByTime"},produces = MediaType.APPLICATION_JSON_VALUE)
	public void appointmentNumByTime(String callback ,HttpServletResponse response){
		Map res = new HashMap<String,String>();

		List<MgUserAppoint> list  = userAppointService.findAll();
		Map<String,List<MgUserAppoint>> mapteacher = list.stream().filter(v->StringUtils.isNotBlank(v.getAppointmentTime()))
				.collect(Collectors.groupingBy(MgUserAppoint::getTeacherName));

		Map<String,Map<String,String>> mapres = new HashMap<String,Map<String,String>>();

		Iterator<String> set  =mapteacher.keySet().iterator();
		while (set.hasNext()){
			String key = set.next();
			List<MgUserAppoint> list2  = mapteacher.get(key);
			Map<String,List<MgUserAppoint>> map2 =  list2.stream().collect(Collectors.groupingBy(v->v.getAppointmentTime()));
			Map<String,String> map3 = new HashMap<>();
			map2.forEach((k,v)->{
				map3.put(k,v.size()>=30?"yes":"no");
				mapres.put(key,map3);
			});
		}

		res.put("status","ok");
		res.put("message",mapres);
		parseJsonToString(res,callback,response);return;
	}


	/**
	 * 预约接口
	 * @param appointmentTime
	 * @param teacherName
	 * @param telephone
	 * @param callback
	 * @param response
	 */
		@RequestMapping(value={"mg/appointment"},produces = MediaType.APPLICATION_JSON_VALUE)
	public void appointment(String appointmentTime,String teacherName,String telephone,String callback ,HttpServletResponse response){
		Map res = new HashMap<String,String>();
		try{

		if(StringUtils.isEmpty(appointmentTime)){
			res.put("status","fail");
			res.put("message","预约时间不能为空！");
			parseJsonToString(res,callback,response);return;
		}
		if(StringUtils.isEmpty(teacherName)){
			res.put("status","fail");
			res.put("message","预约主题不能为空！");
			parseJsonToString(res,callback,response);return;
		}
		if(StringUtils.isEmpty(telephone)){
			res.put("status","fail");
			res.put("message","非常抱歉，暂无留资信息！！");
			parseJsonToString(res,callback,response);return;
		}

		MgUser mgUser = userService.findByTelephone(telephone);

		if(mgUser==null){
			res.put("status","fail");
			res.put("message","非常抱歉，暂无留资信息！");
			parseJsonToString(res,callback,response);return;
		}


		MgUserAppoint mgUserAppoint1 = userAppointService.findByTelephoneAndAppointmentTimeAndTeacherName(telephone, appointmentTime, teacherName);
			if(mgUserAppoint1!=null){
			res.put("status","fail");
			res.put("again","yes");
			res.put("teacher",mgUserAppoint1.getTeacherName());
			res.put("message","已经预约过此时间");
			parseJsonToString(res,callback,response);return ;
		}


		long thisTimeAppointAll = userAppointService.countAllByAppointmentTime(appointmentTime);

		if(thisTimeAppointAll>=30){
			res.put("status","fail");
			res.put("message","此时间段已经预约满了，请您继续关注下一次预约！");
			parseJsonToString(res,callback,response);return;
		}
		MgUserAppoint mgUserAppoint = new MgUserAppoint();
		mgUserAppoint.setTeacherName(teacherName);
		mgUserAppoint.setAppointmentTime(appointmentTime);
		mgUserAppoint.setUserName(mgUser.getUserName());
		mgUserAppoint.setTelephone(telephone);
		mgUserAppoint.setAddress(mgUser.getAddress());
		mgUserAppoint.setBuyCarTime(mgUser.getBuyCarTime());//BuyCarType
		mgUserAppoint.setInterestCarType(mgUser.getInterestCarType());
		mgUserAppoint.setSourceType(mgUser.getSourceType());//mgUserRegisterType
		mgUserAppoint.setUserId(mgUser.getId());
		userAppointService.save(mgUserAppoint);

		res.put("status","ok");
		res.put("message","恭喜您预约成功！");

		   }catch (Exception e){
			res.put("status","ok");
			res.put("message","预约失败，服务器繁忙！");
		}
		parseJsonToString(res,callback,response);return;
	}

	@RequestMapping(value={"mg/sendMgUser"},produces = MediaType.APPLICATION_JSON_VALUE)
	public String sendMgUser(String telephone) throws UnsupportedEncodingException {
		MgUser mgUser = userService.findByTelephone(telephone);
		MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
		params.add("activityname",activityname);//活动名称（请向市场部客户确认，仅用于活动报表数据查询，如“4月A级上海车展”）
		params.add("act","5");
		params.add("track_id","100501 ");
		params.add("username",mgUser.getUserName());
		params.add("mobile",mgUser.getTelephone());
		params.add("terminal_type","1");
		params.add("url",htmlUrl);
		params.add("brand","3362");
		params.add("cartype",getCarType(mgUser.getInterestCarType()));
		return sendToOther(params);
	}

	private final String url="http://app.rteam.cn/mgminiappdrupal/?q=leadssynchronization";

	private String sendToOther(MultiValueMap<String, String> params ) throws UnsupportedEncodingException {
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
		ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
		return URLDecoder.decode(response.getBody(),"UTF-8");
	}

	/**
	 *
	 * 添加用户信息
	 * @param userName
	 * @param appointmentTime
	 * @param teacherName
	 * @param telephone
	 * @param address
	 * @param buyCarTime
	 * @param interestCarType
	 * @param sourceType
	 * @return
	 */
	@RequestMapping(value={"mg/addMgUser"},produces = MediaType.APPLICATION_JSON_VALUE)
	public void addMgUser(String userName,String appointmentTime,String teacherName,String telephone
							,String address,String buyCarTime,String interestCarType,String sourceType,String callback ,HttpServletResponse response) throws UnsupportedEncodingException {

		logger.info("add mgUser,userName:" + userName + "," +
				"appointmentTime:" + appointmentTime + "," +
				"teacherName:" + teacherName + "," +
				"telephone:" + telephone + "," +
				"address:" + address + "," +
				"buyCarTime:" + buyCarTime + "," +
				"interestCarType:" + interestCarType + "," +
				"sourceType:" + sourceType);
        Map res = new HashMap<String,String>();

            if(StringUtils.isEmpty(sourceType)
                    ||StringUtils.isEmpty(userName)
                    ||StringUtils.isEmpty(telephone)
                    //||StringUtils.isEmpty(address)
                    ||StringUtils.isEmpty(buyCarTime)
                    ||StringUtils.isEmpty(interestCarType)){
                res.put("status","fail");
                res.put("message","参数有误！");
                parseJsonToString(res,callback,response);return;
            }

		Pattern pattern = Pattern.compile("1\\d{10}");
		Matcher isNum = pattern.matcher(telephone);
		if(!isNum.matches()){
			res.put("status","fail");
			res.put("message","手机号格式化错误");
			parseJsonToString(res,callback,response);return;
		}

        try{
			MgUser mgUser = userService.findByTelephone(telephone);
			if(mgUser==null){
				mgUser = new MgUser();
			}
			mgUser.setUserName(userName);
			mgUser.setAppointmentTime(appointmentTime);
			mgUser.setTeacherName(teacherName);
			mgUser.setTelephone(telephone);
			mgUser.setAddress(address);
			mgUser.setBuyCarTime(buyCarTime);//BuyCarType
			mgUser.setInterestCarType(interestCarType);
			mgUser.setSourceType(sourceType);//mgUserRegisterType
			userService.saveOrUpdate(mgUser);
		}catch (Exception e){
			res.put("status","fail");
			res.put("message","添加用户异常");
			logger.error("添加用户异常", e);
			parseJsonToString(res,callback,response);return;
		}

		MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
		params.add("activityname",activityname);//活动名称（请向市场部客户确认，仅用于活动报表数据查询，如“4月A级上海车展”）
		params.add("act","5");
		params.add("track_id","100501 ");
		params.add("username",userName);
		params.add("mobile",telephone);
		params.add("terminal_type","1");
		params.add("url",htmlUrl);
		params.add("brand","3362");
		params.add("cartype",getCarType(interestCarType));

		if(isSend){
		    logger.info("发送的参数："+params);
			sendToOther(params);
		}

		res.put("status","ok");
		res.put("message","留资成功！");
		parseJsonToString(res,callback,response);return;
	}



	private String getCarType(String carname){
		carname = carname.trim();
		if(carname.equals("全新名爵6")){
			return "4200";
		}
		if(carname.equals("名爵GT")){
			return "3484";
		}
		if(carname.equals("全新名爵6")){
			return "4200";
		}
		if(carname.equals("全新名爵3")){
			return "3398";
		}
		if(carname.equals("名爵HS")){
			return "4400";
		}
		if(carname.equals("名爵GS")){
			return "3497";
		}
		if(carname.equals("名爵ZS")){
			return "3830";
		}
		if(carname.equals("名爵6新能源")){
			return "4300";
		}
		if(carname.equals("名爵ZS纯电动")){
			return "4500";
		}
		if(carname.equals("名爵E-motion")){
			return "4300";
		}
		if(carname.equals("名爵X-motion")){
			return "4300";
		}
		return "3830";
	}




  /* //并发领取奖品  测试（同一用户并发领取同一个奖品，数据库建立联合唯一索引）（不同用户并发领取奖品 乐观锁）
   final Executor executor = Executors.newCachedThreadPool();

    class ObtainAward implements Runnable{
        private CyclicBarrier cyclicBarrier;
        private String telephone;
        private String awardEnglishName;
        private String gameType;
        private HttpServletResponse response;

        public ObtainAward(CyclicBarrier cyclicBarrier,String telephone,String awardEnglishName,String gameType,HttpServletResponse response){
            this.telephone = telephone;
            this.awardEnglishName = awardEnglishName;
            this.gameType = gameType;
            this.response = response;
            this.cyclicBarrier = cyclicBarrier;
        }
        @Override
        public void run() {
            try {
                logger.info(Thread.currentThread().getName()+":准备同时并发领取奖品.....");
                cyclicBarrier.await();
            }catch (Exception e){

            }
            addMgUserAward(telephone,awardEnglishName,gameType,null,response);
        }
    }


    @RequestMapping(value={"mg/testAddMgUserAward"},produces = MediaType.APPLICATION_JSON_VALUE)
    public void testAddMgUserAward(String  telephone,String awardEnglishName,String gameType,String callback ,HttpServletResponse response,String num){
    	List<MgUser> list = userService.findAll();

        CyclicBarrier cyclicBarrier = new CyclicBarrier(list.size(), new Runnable() {
            @Override
            public void run() {
                logger.info("开始同时并发领取奖品.....");
            }
        });

        for (int i = 0; i < list.size(); i++) {
            executor.execute(new ObtainAward(cyclicBarrier,list.get(i).getTelephone(),awardEnglishName,gameType,response));
        }
        logger.info("完成领取奖品.....");
    }*/

	@RequestMapping(value={"mg/queryMgUserAward"},produces = MediaType.APPLICATION_JSON_VALUE)
	public void queryMgUserAward(String callback ,HttpServletResponse response){
		List<MgAward> list = awardService.findAll();
		Map res = new HashMap<String,String>();
		res.put("status","ok");
		res.put("message",list);
		parseJsonToString(res,callback,response);return;
	}

    @RequestMapping(value={"mg/addMgUserAward"},produces = MediaType.APPLICATION_JSON_VALUE)
    public void addMgUserAward(String  telephone,String awardEnglishName,String gameType,String callback ,HttpServletResponse response){

        logger.info("addMgUserAward,telephone:"+telephone+","+ "awardName:"+awardEnglishName+","+"gameType:"+gameType+",");

        Map res = new HashMap<String,String>();
		List<MgUserAward> list = new ArrayList<MgUserAward>();
        try{
            if(StringUtils.isEmpty(telephone)){
                res.put("status","fail");
                res.put("message","手机号为空！");
                parseJsonToString(res,callback,response);return;
                
            }
			if(StringUtils.isEmpty(gameType)){
				res.put("status","fail");
				res.put("message","请确认是玩的哪个游戏！");
				parseJsonToString(res,callback,response);return;
			}

			if(StringUtils.isEmpty(awardEnglishName)){
				res.put("status","fail");
				res.put("message","请先填写奖品名称！");
				parseJsonToString(res,callback,response);return;
			}
            MgUser mgUser = userService.findByTelephone(telephone);
            if(mgUser == null){
                res.put("status","fail");
                res.put("message","请先填写留资信息！");
                parseJsonToString(res,callback,response);return;
            }

			MgAward mgAward = awardService.findByAwardEnglishName(awardEnglishName);
			if(mgAward == null){
				res.put("status","fail");
				res.put("message","暂无奖品信息配置");
				parseJsonToString(res,callback,response);return;
			}
			if(mgAward.getNum()<=0){
				res.put("status","fail");
				res.put("message","抱歉，您来晚了，奖品已经被领取完了");
				parseJsonToString(res,callback,response);return;
			}

			List<MgUserAward> mgUserAwar = userAwardService.findByUserIdAndSourceType(mgUser.getId(),gameType);

            if(mgUserAwar.size()>0){
                res.put("status","ok");
                res.put("message",mgUserAwar.get(0));
                logger.info(Thread.currentThread().getName() + ":同一用户每一个游戏只能领取一个奖品！");
                parseJsonToString(res,callback,response);return;
            }

			list = userAwardService.findByUserId(mgUser.getId());
			if(list.size()>3){
				res.put("status","fail");
				res.put("message","同一用户最多只能领取三个奖品！");
				logger.info(Thread.currentThread().getName() + ":同一用户最多只能领取三个奖品！");
				parseJsonToString(res,callback,response);return;
			}

			logger.info("用户："+telephone+",玩了游戏："+ GameType.getDescByName(gameType)+",准备领取:"+AwardEnglishNameType.getDescByName(awardEnglishName));

            //添加用户奖品信息 ，减少奖品库存
            MgUserAward mgUserAward = new MgUserAward();
            mgUserAward.setAwardName(AwardEnglishNameType.getDescByName(awardEnglishName));
            mgUserAward.setCreatedTime(System.currentTimeMillis());
            mgUserAward.setSourceType(gameType);
            mgUserAward.setUserId(mgUser.getId());
            mgAward.setNum(mgAward.getNum()-1);
            mgUserAward.setAwardEnglishName(awardEnglishName);
            entityManageDaoService.addUserAwardInfo(mgAward, mgUserAward);//乐观锁控制并发
        }catch (Exception e){
            res.put("status","fail");
            res.put("message","系统繁忙，请您稍后再试");
            logger.info(Thread.currentThread().getName()+":领取用户奖品异常，请联系工作人员！"+e.getMessage());
            parseJsonToString(res,callback,response);return;
        }

        res.put("status","ok");
        res.put("message","领取奖品成功！");
		res.put("award",list);
        parseJsonToString(res, callback, response);return;
    }

    private void parseJsonToString(Map map,String callback,HttpServletResponse response) {
		 response.setContentType("text/javascript");
		try {
			Writer writer = response.getWriter();
			writer.write(callback+"(");
			writer.write(JSON.toJSONString(map));
			writer.write(")");
			writer.close();
			writer.flush();
		} catch (IOException e) {

		}
	}
}
